# -*- coding: utf-8 -*-

import time
import logging

import redis

REDIS_LATEST_UPDATE_KEY = 'latest_update'

logger = logging.getLogger(__name__)


class RedisInterface(object):
    def __init__(self, app=None):
        self.pool = None
        self.redis = None
        self.app = None
        self.sub_to_poll_threshold = None

        if app is not None:
            self.init_app(app)

    def init_app(self, app):
        self.app = app

        app.config.setdefault('REDIS_HOST', '127.0.0.1')
        app.config.setdefault('REDIS_PORT', 6379)
        app.config.setdefault('REDIS_DB', 9)
        app.config.setdefault('SUBSCRIBE_TO_POOL_THRESHOLD', 60 * 20)

        self.pool = redis.ConnectionPool(
            host=app.config['REDIS_HOST'],
            port=app.config['REDIS_PORT'],
            db=app.config['REDIS_DB'],
            password=app.config.get('REDIS_PASSWORD'),
        )
        self.redis = redis.StrictRedis(connection_pool=self.pool)
        app.redis = self
        app.redis_ins = self.redis

        self.sub_to_poll_threshold = app.config['SUBSCRIBE_TO_POLL_THRESHOLD']

    def enable_publisher(self, publisher):
        member = '{}.publisher'.format(publisher.username)
        latest = self.redis.zscore(
            REDIS_LATEST_UPDATE_KEY,
            member
        )
        if (int(time.time()) - int(latest)) > self.sub_to_poll_threshold:
            logger.info('Add publisher to head of polling queue. %s', publisher.username)
            self.redis.zadd(
                REDIS_LATEST_UPDATE_KEY,
                0,
                member
            )

    def disable_publisher(self, publisher):
        self.redis.zrem(
            REDIS_LATEST_UPDATE_KEY,
            '{}.publisher'.format(publisher.username)
        )

    def enable_hashtag(self, hashtag):
        self.redis.zadd(
            REDIS_LATEST_UPDATE_KEY,
            0,
            '{}.hashtag'.format(hashtag.name)
        )

    def disable_hashtag(self, hashtag):
        self.redis.zrem(
            REDIS_LATEST_UPDATE_KEY,
            '{}.hashtag'.format(hashtag.name)
        )
